<template>
    <el-container style="height: 100vh; flex-direction: column;">
        <!-- 头部 -->
        <el-header
            style="background-color: #409EFF; color: white; display: flex; align-items: center; justify-content: space-between;">
            <h2 style="margin: 0;">图书馆管理系统</h2>
            <div style="display: flex; align-items: center;">
                <el-input v-model="searchKeyword" placeholder="请输入图书名称或作者" style="width: 300px;" @input="filterBooks">
                    <template #append>
                        <el-button icon="Search" @click="filterBooks"></el-button>
                    </template>
                </el-input>
            </div>
        </el-header>

        <!-- 主体内容 -->
        <el-main style="padding: 20px;">
            <el-row :gutter="20">
                <!-- 分类栏 -->
                <el-col :span="6">
                    <el-card class="category-card">
                        <div class="el-card__header">
                            <strong>图书分类</strong>
                        </div>
                        <ul>
                            <li v-for="category in categories" :key="category.id"
                                :class="['category-item', { active: selectedCategory === category.id }]"
                                @click="selectCategory(category.id)">
                                {{ category.name }}
                            </li>
                        </ul>
                    </el-card>
                </el-col>

                <!-- 图书展示 -->
                <el-col :span="18">
                    <el-card class="book-list-card">
                        <div class="el-card__header">
                            <span><strong>图书列表</strong></span>
                            <el-button style="float: right;" type="primary"
                                :disabled="borrowList.length >= maxBorrowLimit" @click="addToBorrowList">
                                加入借阅清单
                            </el-button>
                        </div>

                        <!-- 图书网格 -->
                        <el-row :gutter="20">
                            <el-col v-for="book in paginatedBooks" :key="book.id" :span="6"
                                style="margin-bottom: 20px;">
                                <el-card class="book-card" shadow="hover" @click="handleBookClick(book)"
                                    :style="{ borderColor: isSelected(book.id) ? '#409EFF' : 'transparent' }">
                                    <img :src="book.image" alt="图书封面"
                                        style="width: 100%; height: 200px; object-fit: cover; margin-bottom: 10px;" />
                                    <div style="display: flex; align-items: center; justify-content: space-between;">
                                        <span>{{ book.title }}</span>
                                        <el-checkbox :model-value="isSelected(book.id)"
                                            @update:model-value="toggleSelection(book.id)" @click.stop />
                                    </div>
                                    <p style="color: #999;">作者：{{ book.author }}</p>
                                    <p style="color: red;">￥{{ book.price }}</p>
                                </el-card>
                            </el-col>
                        </el-row>

                        <!-- 分页组件 -->
                        <div style="text-align: center; margin-top: 20px;">
                            <el-pagination layout="prev, pager, next" :page-size="pageSize"
                                :total="filteredBooks.length" v-model="currentPage" background />
                        </div>
                    </el-card>
                </el-col>
            </el-row>

            <!-- 借阅清单 -->
            <el-row style="margin-top: 30px;">
                <el-col :span="24">
                    <el-card class="borrow-list-card">
                        <div class="el-card__header">
                            <span><strong>借阅清单</strong></span>
                            <el-button style="float: right; margin-left: 10px;" type="danger"
                                @click="clearBorrowList">清空清单</el-button>
                            <el-button style="float: right;" type="warning" @click="batchReturnBooks"
                                :disabled="borrowedList.length === 0">批量归还</el-button>
                            <el-button style="float: right;" type="success" @click="submitBorrowList">提交借阅申请</el-button>
                        </div>

                        <div v-if="borrowList.length > 0">
                            <el-table :data="borrowList" border style="width: 100%">
                                <el-table-column prop="title" label="图书名称" width="200"></el-table-column>
                                <el-table-column prop="author" label="作者" width="150"></el-table-column>
                                <el-table-column prop="price" label="价格" width="100"></el-table-column>
                                <el-table-column label="借阅状态" width="120">
                                    <template #default="{ row }">
                                        <el-tag type="success" v-if="row.borrowed">已借阅</el-tag>
                                        <el-tag type="info" v-else>待处理</el-tag>
                                    </template>
                                </el-table-column>
                                <el-table-column label="操作" width="120">
                                    <template #default="{ row }">
                                        <el-button v-if="row.borrowed" size="small" type="danger"
                                            @click="returnBook(row)">
                                            归还
                                        </el-button>
                                    </template>
                                </el-table-column>
                            </el-table>
                            <div style="margin-top: 20px; font-weight: bold;">
                                已选书籍数量：{{ borrowList.length }} / 最多可借：{{ maxBorrowLimit }}
                            </div>
                        </div>
                        <div v-else style="text-align: center; color: #999; padding: 20px;">
                            借阅清单为空
                        </div>
                    </el-card>
                </el-col>
            </el-row>
        </el-main>
    </el-container>

    <!-- 图书详情弹窗 -->
    <el-dialog v-model="dialogVisible" title="图书详情" width="30%">
        <div>
            <p><strong>书名：</strong>{{ selectedBook?.title }}</p>
            <p><strong>作者：</strong>{{ selectedBook?.author }}</p>
            <p><strong>价格：</strong>￥{{ selectedBook?.price }}</p>
            <p><strong>库存：</strong>{{ selectedBook?.quantity }}</p>
            <p><strong>出版社：</strong>{{ selectedBook?.publisher }}</p>
        </div>
        <template #footer>
            <el-button @click="dialogVisible = false">关闭</el-button>
        </template>
    </el-dialog>

    <!-- 学生信息弹窗 -->
    <el-dialog v-model="studentDialogVisible" title="填写学生信息" width="30%">
        <el-form ref="formRef" :model="studentForm" label-width="80px" :rules="rules"
            @submit.prevent="submitStudentInfo">
            <el-form-item label="学生姓名" prop="name">
                <el-input v-model="studentForm.name" />
            </el-form-item>
            <el-form-item label="学号" prop="studentId">
                <el-input v-model.number="studentForm.studentId" />
            </el-form-item>
            <el-form-item style="margin-top: 20px;">
                <el-button type="primary" native-type="submit">提交</el-button>
                <el-button @click="resetForm">取消</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import libraryApi from '@/api/manage/libraryApi'; // 替换为你实际的 API 路径

// ===== 状态定义 =====
const maxBorrowLimit = 5;

// 图书相关
const books = ref([]);
const categories = ref([]);
const currentPage = ref(1);
const pageSize = 8;
const searchKeyword = ref('');
const selectedCategory = ref(0);

// 勾选图书 ID
const selectedBookIds = ref([]);

// 借阅清单
const borrowList = ref([]);

// 弹窗相关
const dialogVisible = ref(false);
const selectedBook = ref(null);

// 新增 - 学生信息弹窗
const studentDialogVisible = ref(false);
const studentForm = ref({
    name: '',
    studentId: null,
});
const formRef = ref();

// 表单验证规则
const rules = {
    name: [
        { required: true, message: '请输入学生姓名', trigger: 'blur' },
        { min: 2, max: 5, message: '姓名长度应在2到5个字符之间', trigger: 'blur' }
    ],
    studentId: [
        { required: true, message: '请输入学号', trigger: 'blur' },
        {
            validator: (rule, value, callback) => {
                const reg = /^\d{1,10}$/;
                if (!reg.test(value)) {
                    callback(new Error('请输入1~10位数字'));
                } else {
                    callback();
                }
            },
            trigger: 'blur'
        }
    ]
};

// ===== 过滤与分页逻辑 =====
const filteredBooks = computed(() => {
    let result = [...books.value];
    if (selectedCategory.value !== 0) {
        result = result.filter((book) => book.categoryId === selectedCategory.value);
    }
    if (searchKeyword.value.trim()) {
        const keyword = searchKeyword.value.toLowerCase();
        result = result.filter(
            (book) =>
                book.title.toLowerCase().includes(keyword) || book.author.toLowerCase().includes(keyword)
        );
    }
    return result;
});

const paginatedBooks = computed(() => {
    const start = (currentPage.value - 1) * pageSize;
    const end = start + pageSize;
    return filteredBooks.value.slice(start, end);
});

const borrowedList = computed(() => {
    return borrowList.value.filter(book => book.borrowed);
});

// ===== 方法定义 =====
function getCategory() {
    libraryApi.getCategories().then(response => {
        categories.value = response.data.data.map(item => ({
            id: item.id,
            name: item.categoryName
        }));
    }).catch(() => {
        ElMessage.error('获取分类数据失败');
    });
}

function getBooks() {
    libraryApi.getBooks().then(response => {
        books.value = response.data.data.map(item => ({
            id: item.id,
            title: item.bookName,
            author: item.author,
            price: item.price,
            categoryId: item.categoryId,
            image: item.cover,
            quantity: item.quantity,
            publisher: item.publisher
        }));
    }).catch(() => {
        ElMessage.error('获取图书数据失败');
    });
}

function isSelected(id) {
    return selectedBookIds.value.includes(id);
}

function toggleSelection(id) {
    const index = selectedBookIds.value.indexOf(id);
    if (index === -1) {
        selectedBookIds.value.push(id);
    } else {
        selectedBookIds.value.splice(index, 1);
    }
}

function addToBorrowList() {
    const selectedBooks = books.value.filter((book) => isSelected(book.id));
    if (selectedBooks.length === 0) {
        ElMessage.info('请先选择要加入的图书');
        return;
    }

    selectedBooks.forEach((book) => {
        if (!isInBorrowList(book.id)) {
            if (borrowList.value.length >= maxBorrowLimit) {
                ElMessage.warning(`最多只能借阅 ${maxBorrowLimit} 本`);
                return;
            }
            borrowList.value.push({ ...book });
        }
    });

    selectedBookIds.value = [];
    saveToLocalStorage();
}

function isInBorrowList(id) {
    return borrowList.value.some((item) => item.id === id);
}

function clearBorrowList() {
    borrowList.value = [];
    saveToLocalStorage();
}

function submitBorrowList() {
    if (borrowList.value.length === 0) {
        ElMessage.info('请先选择要借阅的图书');
        return;
    }
    studentDialogVisible.value = true;
}

function selectCategory(id) {
    selectedCategory.value = id;
    currentPage.value = 1;
}

function showBookDetail(book) {
    selectedBook.value = book;
    dialogVisible.value = true;
}

function handleBookClick(book) {
    const target = event.target;
    if (
        target.classList.contains('el-checkbox') ||
        target.closest('.el-checkbox') ||
        target.tagName.toLowerCase() === 'input'
    ) {
        return;
    }
    showBookDetail(book);
}

function updateCheckedStatus() {
    const idsInBorrowList = borrowList.value.map((b) => b.id);
    selectedBookIds.value = idsInBorrowList;
}

function saveToLocalStorage() {
    localStorage.setItem('borrowList', JSON.stringify(borrowList.value));
}

// 提交学生信息
function submitStudentInfo() {
    formRef.value.validate((valid) => {
        if (valid) {
            const studentId = studentForm.value.studentId;
            const today = new Date().toISOString().split('T')[0];

            // 设置每本书的状态
            borrowList.value.forEach((book) => {
                book.borrowed = true;
                book.studentId = studentId;
                book.returnDate = null;
            });

            // 提交到后端
            libraryApi.submitBorrow({
                books: borrowList.value.map(b => b.id),
                userId: studentId,
                borrowDate: today
            }).then(response => {
                // 👇 判断后端是否真正成功
                if (response && response.code === 200) { // 假设后端返回 code=200 表示成功
                    ElMessage.success(`借阅申请已提交给 ${studentForm.value.name}`);
                    saveToLocalStorage();
                    studentDialogVisible.value = false;
                    resetForm();
                } else {
                    ElMessage.error('提交失败！' + response.data.msg);
                    // 回滚图书状态
                    borrowList.value.forEach(book => {
                        book.borrowed = false;
                        book.studentId = null;
                        book.returnDate = null;
                    });
                }
            }).catch(err => {
                console.error('提交借阅申请失败:', err);
                ElMessage.error('网络异常，请重试');
                // 回滚图书状态
                borrowList.value.forEach(book => {
                    book.borrowed = false;
                    book.studentId = null;
                    book.returnDate = null;
                });
            });
        }
    });
}

// 重置表单并关闭弹窗
function resetForm() {
    formRef.value.resetFields();
    studentDialogVisible.value = false;
}

// 归还图书
function returnBook(book) {
    ElMessageBox.confirm('确定要归还这本书吗？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        const now = new Date().toISOString();
        libraryApi.returnBook(book.id, book.studentId).then(() => {
            book.returnDate = now;
            book.borrowed = false;
            saveToLocalStorage();
            ElMessage.success('图书已成功归还');
        }).catch(() => {
            ElMessage.error('归还失败，请重试');
        });
    });
}

// 批量归还图书
function batchReturnBooks() {
    ElMessageBox.confirm('确定要归还选中的所有图书吗？', '批量归还', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        const now = new Date().toISOString();
        const promises = [];

        borrowedList.value.forEach(book => {
            promises.push(libraryApi.returnBook(book.id, book.studentId));
            book.returnDate = now;
            book.borrowed = false;
        });

        Promise.all(promises)
            .then(() => {
                saveToLocalStorage();
                ElMessage.success('所选图书已成功归还');
            })
            .catch(() => {
                ElMessage.error('部分图书归还失败，请重试');
            });
    });
}

onMounted(() => {
    getCategory();
    getBooks();
    const saved = localStorage.getItem('borrowList');
    if (saved) {
        try {
            const parsed = JSON.parse(saved);
            borrowList.value = parsed;
            updateCheckedStatus();
        } catch (e) {
            console.warn('无法解析本地借阅数据');
        }
    }
});
</script>

<style scoped>
/* 分类样式 */
.category-card .category-item {
    cursor: pointer;
    padding: 10px;
    transition: background-color 0.3s;
}

.category-card .category-item:hover,
.category-card .category-item.active {
    background-color: #f0f0f0;
}

/* 图书卡片样式 */
.book-card img {
    border-radius: 4px;
    cursor: pointer;
}

.book-card:hover {
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.book-card[style*='border-color: rgb(64, 158, 255)'] {
    border-color: #409eff !important;
}

/* 借阅清单样式 */
.borrow-list-card .el-table {
    margin-bottom: 20px;
}
</style>